﻿using GiteePlugin.Configuration;
using GiteePlugin.Core.Auth;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GiteePlugin.Core.Authentication.AuthProvider
{
    public class DefaultAuthProvider : IGiteeAuthProvider
    {
        private readonly GiteeAuthConfig _config;
        private readonly IGiteeAuthApi _authApi;

        public DefaultAuthProvider(
            IOptions<GiteeAuthConfig> config,
            IGiteeAuthApi authApi)
        {
            _config = config.Value;
            _authApi = authApi;
        }

        public Task<string> BuildAuthorizationUrl(string state)
        {
            throw new NotImplementedException();
        }

        public Task ExchangeCodeAsync(string code)
        {
            throw new NotImplementedException();
        }

        public async Task<string> GetAccessTokenAsync(string code)
        {
            var parameters = new OAuthTokenRequest { Code = code, ClientId = _config.ClientId, ClientSecret = _config.ClientSecret };
            var response = await _authApi.GetAccessToken(parameters);
            return response.AccessToken;
            //if (!string.IsNullOrEmpty(_tokenCache.AccessToken) &&
            //    DateTime.Now < _tokenCache.ExpireTime)
            //{
            //    return _tokenCache.AccessToken;
            //}

            //var response = await _authApi.RefreshTokenAsync(new RefreshTokenRequest
            //{
            //    GrantType = "refresh_token",
            //    RefreshToken = _tokenCache.RefreshToken
            //});

            //UpdateTokenCache(response);
        }

        private void UpdateTokenCache(AuthTokenResponse response)
        {
            //_tokenCache.ExpireTime = DateTime.Now.AddSeconds(response.ExpiresIn - 300); // 提前5分钟过期
        }
    }
}
